//
//  ExpertViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/1.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "ExpertListV2ViewModel.h"

#import "ExpertListCellModel.h"

@interface ExpertListV2ViewModel ()

@property (nonatomic, strong) RACCommand* expertCmd;
@property (nonatomic, strong) RACCommand* consultCmd;

@end

@implementation ExpertListV2ViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.lastPage = 100;
    self.shouldMultiSections = NO;
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.expertCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
        {
            [subscriber sendNext:input];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.consultCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        if ([um isLogined])
        {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                    {
                        [subscriber sendNext:input];
                        [subscriber sendCompleted];
                        
                        return nil;
                    }];
        }
        else
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请登录后再操作"}]];
        }
    }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_consult_expertlist params:interface_param_consult_expertlist(@(page + 1), @(List_PageSize))] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    ExpertsListData* listData = [ExpertsListData modelWithJSON:x];
                    
                    NSArray *viewModels = [listData.datas.rac_sequence map:^ExpertListCellModel *(ExpertsListData* data)
                                           {
                                               @strongify(self);
                                               
                                               @weakify(self);
                                               ExpertListCellModel *itemViewModel = [[ExpertListCellModel alloc] initWithData:data cellHeight:self.cellHeight];
                                               [[itemViewModel.expertCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
                                               {
                                                   @strongify(self);
                                                   
                                                   [self.expertCmd execute:x];
                                               }];
                                               
                                               [[itemViewModel.consultCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
                                               {
                                                   @strongify(self);
                                                   
                                                   [self.consultCmd execute:x];
                                               }];
                                               
                                               return itemViewModel;
                                           }].array;
                    
                    if (viewModels == nil || viewModels.count < List_PageSize)
                    {
                        self.lastPage = self.page;
                        
                        if (viewModels == nil)
                            viewModels = @[];
                    }
                    else
                    {
                        self.lastPage = 999;
                    }
                    
                    if (self.shouldPullUpToLoadMore)
                    {
                        if (0 == page)
                        {
                            self.dataSource = viewModels;
                        }
                        else
                        {
                            if (self.dataSource == nil)
                            {
                                self.dataSource = viewModels;
                            }
                            else
                            {
                                self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                            }
                        }
                    }
                    else
                    {
                        self.dataSource = viewModels;
                    }
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

@end
